import api from '../../api/index'
import Toast from '@vant/weapp/toast/toast';
import CONFIG from '../../utils/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerList: [], //首页轮播图
    ossHostBanner: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/dailyAttendance/WechatIMG1480.jpg',
    sportclassbanner: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/sportclassbanner.jpg',
    data_dev: [{
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/1.png',
      name: '健康监测',
      url: '/healthMonitoring/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/2.png',
      name: '红星新闻',
      url: '/redStarNews/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/3.png',
      name: '健康档案',
      url: '/healthRecords/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/4.png',
      name: '健康妙招',
      url: '/healthTips/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/5.png',
      name: '健康咨询',
      url: '/healthCounseling/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/6.png',
      name: '运动推荐',
      url: '/sportsRecommendations/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/7.png',
      name: '饮食推荐',
      url: '/dietaryRecommendations/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/8.png',
      name: '情志推荐',
      url: '/emotionalRecommendation/pages/home/index'
    }],
    daily_data_dev: [{
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/9.png',
      name: '体重管理',
      url: '/weightManagement/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/10.png',
      name: '睡眠管理',
      url: '/sleepManagement/pages/home/index'
      // url: ''
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/11.png',
      name: '慢病管理',
      url: '/chronicDiseaseManagement/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/12.png',
      name: '运动管理',
      url: '/sportsAdministration/pages/home/index'
    }],
    live_data_dev: [{
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/manbing.png',
      name: '慢病管理',
      url: '/chronicDiseaseManagement/pages/home/index'
    },
    {
      imgurl: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/home/yundong.png',
      name: '运动管理',
      url: '/sportsAdministration/pages/home/index'
    }],
    getvideolist: null,
    getlivelist: null,
    sports: null,
    messageshow: false,
    getclasslist: [],
    tags: '',
    showclass: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // wx.setStorageSync('accessToken', 'JSESSIONID=ZTJjODYwNTYtZDhiYS00MWEwLThhMTQtNDY4NGRmMjdmZmY0; Path=/; HttpOnly; SameSite=Lax');
    // this.userload()
    // return
    // 自定义加载图标
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    wx.removeStorage({
      key: 'newskindid',
      success(res) {
      }
    })
    const {mirrorcode} = options
    if(mirrorcode) {
      this.setData({
        mirrorcode
      });
      this.loginToMirror(mirrorcode)
    }
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        messageshow: true
      });
      this.userload()
      this.getBannerData()
      this.getVadioData()
      this.getLiveData()
      this.getClassData()
    } else {
      this.setData({
        messageshow: false,
        showclass: false
      });
    }
  },
  loginToMirror() {
    let data = {
      'logintime': '5'
    }
      let url = `https://mirror.laikang.com/api/inspectionmirror/public/login/pushLoginToMirrorApp?mirrorCode=${this.data.mirrorcode}`

    api.adminPost(url, { data }).then(res => {
      console.log('请求成功:', res.data);
      Toast('扫码登录成功');
    }).catch(e => {
        console.log(e)
        // Toast('请登录');
    })
  },
  /**
     * 获取视频列表
     */
	async getClassData() {
		// console.log('getBanner')
		try {
			const getclasslist = await this.getClassload();
      console.log(getclasslist);
      for (let i = 0; i < getclasslist.length; i++) {
        if(!getclasslist[i].images) {
          getclasslist[i].images = 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/error2.png'
        } 
      }
      console.log(getclasslist);
			this.setData({
        getclasslist,
        showclass: true
			});
		} catch (e) {
			console.error(e);
		}
  },
  async getClassload() {
    try {
      const res = await api.post('/api/hxhealth/sportvideo/group', {
          data: {
              'tags': this.data.tags
          }
      })
      return res
  } catch (e) {
      console.log('getClassload->', e)
      return null
  }
  },
  async getvideoloadmoren() {
    console.log('meiyouzou--------???--');
    try {
      const res = await api.post('/api/hxhealth/sportvideo/group', {
          data: {
              'tags': '日常调养'
          }
      })
      console.log(res);
      for (let i = 0; i < res.length; i++) {
        if(!res[i].images) {
          res[i].images = 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/error2.png'
        } 
      }
      console.log(res);
			this.setData({
				getclasslist: res
			});
  } catch (e) {
      console.log('getClassload->', e)
      return null
  }
  
  },
  govadio(e) {
    console.log(e.currentTarget.dataset);
    const {titlename,video,content,id} = e.currentTarget.dataset
    console.log(titlename);
    wx.navigateTo({
      url: `/sportsClass/pages/video/index?titlename=${titlename}&articleId=${id}&video=${video}&content=${content}`
  })
  },
  goChange() {
    wx.navigateTo({
      url: `/sportsClass/pages/height/index`
  })
  },
  goMessage() {
    wx.navigateTo({ url: '/message/pages/home/index' });
  },
  judgingLogin() {
    wx.getStorage({
      key: 'accessToken',
      success: (res) => {
        console.log(res.data)
        // this.getinfo()
        this.getTicket()
        if (!res.data) {
          this.getorg()
        }
      },
      fail: (error) => {
        console.log(error);
        this.getorg()
      }
    })
  },
  getorg() {
    const actions = {
      data: {},
      head: {}
    };
    try {
      api.get(`/api/hxhealth/login/orgapp/${CONFIG.orgCode}/${CONFIG.appCode}`, actions, true).then((res) => {
        console.log(res);
        console.log(res.head['Set-Cookie']);
        if (res.head['Set-Cookie']) {
          wx.setStorageSync('accessToken', res.head['Set-Cookie']);
          this.getvideoloadmoren()
        }
        
      });
    } catch (e) {
      console.error(e);
    }
  },
  getinfo () {
    try {
      api.get(`/api/user/info`).then((res) => {
        console.log(res);
      });
    } catch (e) {
      console.error(e);
    }
  },
  async getTicket() {
    try {
      const list = await api.post('/api/hxhealth/user/laikangticket')
      console.log(list);
      this.getTickettologin(list[0].url, list[0].ticket)
    } catch (e) {
      console.log(e);
    }
  },
  async getTickettologin(url, ticketvalue) {
    console.log(`${url}/api/login/ticket/${ticketvalue}?`);
    try {
      const res = await api.ApiCookieGet(`${url}/api/login/ticket/${ticketvalue}?`)
      console.log(res);
      console.log(res.head['Set-Cookie']);
      wx.setStorageSync('LKaccessToken', res.head['Set-Cookie'])
      return res
    } catch (e) {
      return null
    }
  },
  async getBannerList() {
    try {
      const res = await api.post('/api/hxhealth/banner/list', {
        data: {
          'name': ''
        }
      })
      setTimeout(() => {
        Toast.clear();
      }, 800)
      return res
    } catch (e) {
      console.log('getBannerList->', e)
      return null
    }
  },

  async getliveload() {
    try {
      const res = await api.post('/api/hxhealth/alive/list', {
        data: {
          alivePlayState: '-1',
          'name': ''
        }
      })
      return res
    } catch (e) {
      console.log('getvideoload->', e)
      return null
    }
  },
  async getvideoload() {
    try {
      const res = await api.post('/api/hxhealth/video/list', {
        data: {
          'name': ''
        }
      })
      return res
    } catch (e) {
      console.log('getvideoload->', e)
      return null
    }
  },
  userload() {
    console.log('加载userInfo');
    // 整体列表查询
    api.post('/api/hxhealth/user/load').then((res) => {
      // console.log(res);
      console.log('----res----', res[0])
      this.setData({
        userlist: res[0]
      });
      wx.setStorageSync('userInfo', res[0])
      this.gethxhealthsporttags()
    })
  },
  // 一进入首页判断是否第一次进入
  async gethxhealthsporttags() {
    try {
      const res = await api.post('/api/user/storage/get', {
        data: {
          'key': 'hxhealthsporttags'
        }
      })
      let array = res
      if (array && array.length > 0 && array[0].value) {
        // 有选择
        console.log('有选择--------');
        try {
          console.log(array[0].value);
          console.log(typeof array[0].value);
          array = JSON.parse(array[0].value)
          console.log("字符串包含对象--------:", array);
          if (!array.sporttagsfirst) {
            wx.navigateTo({ url: '/sportsClass/pages/height/index' });
          }
        } catch (error) {
          console.log("字符串是纯文本------2--:", array);
          // wx.navigateTo({ url: '/sportsClass/pages/height/index' });
          wx.hideLoading()
        }

      } else {
        // 没有选择
        console.log('没有选择--------');
        wx.navigateTo({ url: '/sportsClass/pages/height/index' });
        wx.hideLoading()
      }
    } catch (e) {
      console.log('catchget->', e)
      return null
    }
  },
  // 点击进入课程并且已经登录
  async get() {
    try {
      const res = await api.post('/api/user/storage/get', {
        data: {
          'key': 'hxhealthsporttags'
        }
      })
      let array = res[0].value
      console.log(res[0].value);
      console.log('----00000---');
      if (typeof array === 'string' && array) {
        try {
          array = JSON.parse(array)
          console.log("字符串包含对象1111:", array);
          if (array && typeof array === 'object' && !Array.isArray(array)) {
            console.log(array);
            if (array.tags) {
              wx.reLaunch({
                url: `/sportsClass/pages/home/index?tags=${array.tags}`
              })
            } else {
              wx.reLaunch({
                url: `/sportsClass/pages/height/index`
              })
            }
          } else {
            this.setData({
              loading: false
            });
            wx.hideLoading()
          }
        } catch (error) {
          console.log("字符串是纯文本2222:", array);
          wx.navigateTo({
            url: `/sportsClass/pages/home/index?tags=${array.tags}`
          })
        }
      } else {
        wx.navigateTo({
          url: `/sportsClass/pages/height/index`
        })
      }
    } catch (e) {
      console.log('get->', e)
      return null
    }
  },
  /**
     * 获取首页banner
     */
  async getBannerData() {
    // console.log('getBanner')
    try {
      const banner = await this.getBannerList()
      console.log(banner)
      this.setData({
        bannerList: banner
      })
    } catch (e) {
      console.error(e)
    }
  },
  /**
     * 跳转到直播列表
     */
  goLive() {
    wx.navigateTo({
      url: `/live/pages/home/index`
    })
  },
  /**
     * 获取直播中心列表
     */
  async getLiveData() {
    // console.log('getBanner')
    try {
      const getlivelist = await this.getliveload()
      console.log(getlivelist);
      if (getlivelist) {
        for (let i = 0; i < getlivelist.length; i++) {
          if (!getlivelist[i].images) {
            getlivelist[i].images = 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/error2.png'
          }
        }
        console.log(getlivelist)
        this.setData({
          getlivelist
        })
      }
    } catch (e) {
      console.error(e)
    }
  },
  /**
     * 获取视频中心列表
     */
  async getVadioData() {
    // console.log('getBanner')
    try {
      const getvideolist = await this.getvideoload()
      for (let i = 0; i < getvideolist.length; i++) {
        if (!getvideolist[i].images) {
          getvideolist[i].images = 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/error2.png'
        }

      }
      console.log(getvideolist)
      this.setData({
        getvideolist
      })
    } catch (e) {
      console.error(e)
    }
  },
  onVadioClick() {
    wx.navigateTo({
      url: `/videoplayer/pages/home/index?`
    })
  },
  onSportsClick() {
    console.log('进入运动课程前');
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res.data)
        if (res.data) {
          this.get()
        } else {
          wx.navigateTo({
            url: `/sportsClass/pages/home/index?tags=减脂减重,疾病康养,日常调养,体态修复,抗衰益智`
          })
        }
      },
      fail: (error) => {
        console.log(error);
        wx.navigateTo({
          url: `/sportsClass/pages/home/index?tags=减脂减重,疾病康养,日常调养,体态修复,抗衰益智`
        })
      }
    })
  },
  async goLiveDetail(e) {
    const { pageurl } = e.currentTarget.dataset;
    const actions = {
      data: {
        loginType: '4',
        redirectUri: `${pageurl}?app_env_type=mini_program_wechat_sdk`,
      }
    }
    const result = await api.post(`/api/user/xiaoetech/redirecturi`, actions)
    if (result[0]) {
      wx.navigateTo({
        url: `/live/pages/detail/index`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromOpenedPage: (data) => {//参数名字随便起，前后页面对应上即可
            //对发送回来的数据进行处理
            console.log(data)
          },
          someEvent: (data) => {//参数名字随便起，前后页面对应上即可
            console.log(data)
          }
        },
        success: (res) => {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('acceptDataFromOpenerPage', { data: result[0].loginUrl })//参数名字随便起，前后页面对应上即可
        },
      })
    }
  },
  go(e) {
    console.log(e);
    const { titlename, urlpage } = e.currentTarget.dataset;
    console.log(urlpage, 'page111', titlename)
    wx.getStorage({
      key: 'accessToken',
      success: (res) => {
        console.log(res.data)
        console.log(urlpage);
        if (urlpage && res.data) {
          console.log('1');
          wx.navigateTo({
            url: `${urlpage}?titlename=${titlename}`
          })
        } else if (!urlpage && res.data) {
          console.log('2');
          wx.showToast({
            title: '正在开发，敬请期待',
            icon: 'none',
            duration: 3000
          })
        } else if (titlename == '红星新闻') {
          console.log('3');
          wx.navigateTo({
            url: `${urlpage}?titlename=${titlename}`
          })
        } else if (titlename == '健康监测') {
          console.log('3');
          wx.navigateTo({
            url: `${urlpage}?titlename=${titlename}`
          })
        } else {
          wx.navigateTo({
            url: `${urlpage}?titlename=${titlename}`
          })
          // wx.navigateTo({
          //   url: `/pages/login/qrcode`
          // })
        }
      },
      fail: (error) => {
        console.log(error);
        wx.navigateTo({
          url: `${urlpage}?titlename=${titlename}`
        })
        //   if (titlename == '红星新闻') {
        //     wx.navigateTo({
        //       url: `${urlpage}?titlename=${titlename}`
        //     })
        // } else {
        //   wx.navigateTo({
        //     url: `/pages/login/qrcode`
        //   })
        // }
      }
    })
  },
  goVadio(e) {
    console.log(e.currentTarget.dataset);
    const { titlename, video, content, id } = e.currentTarget.dataset
    console.log(titlename);
    wx.navigateTo({
      url: `/videoplayer/pages/video/index?titlename=${titlename}&video=${video}&content=${content}&articleId=${id}`
    })
  },
  goClass(e) {
    console.log(e.currentTarget.dataset);
    const { titlename, video, content } = e.currentTarget.dataset
    console.log(titlename);
    wx.navigateTo({
      url: `/videoplayer/pages/play/index?titlename=${titlename}&video=${video}&content=${content}`
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.judgingLogin()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})